<?php
namespace system\libraries;

use system\core\Config;

class Encrypt 
{
    private $_key;
    
    private $_cipher = MCRYPT_RIJNDAEL_256;
    
    private $_mode = MCRYPT_MODE_CBC;   
    
    /**
     * Constructor
     */
    public function __construct()
    {
        $key = Config::get('config', 'encryption_key');
        
        if ( $key == '' )
        {
            throw new \Exception('In order to use the Encrypt class, you must specify a encryption key in your config file.');
        }
        
        $this->_key = mhash(MHASH_SHA256, $key);
    }
    
    /**
     * Set encryption key
     * 
     * @param string $key 
     */
    public function setKey( $key )
    {
        $this->_key = $key;
    }
    
    /**
     * Encode
     * 
     * @param string $data
     * @return string
     */
    public function encode( $data )
    {
        return base64_encode( $this->_mcryptEncode($data) );
    }
    
    /**
     * Decode
     * 
     * @param string $data
     * @return string
     */
    public function decode( $data )
    {
        return $this->_mcryptDecode( base64_decode($data) );
    }
    
    /**
     * Mcrypt Encode
     * 
     * @param string $data
     * @return string
     */
    private function _mcryptEncode( $data )
    {
        $ivSize = mcrypt_get_iv_size($this->_cipher, $this->_mode);
	$iv = mcrypt_create_iv($ivSize, MCRYPT_RAND);
        
        return $iv.mcrypt_encrypt($this->_cipher, $this->_key, $data, $this->_mode, $iv);
    }
    
    /**
     * Mcrypt Decode
     */
    private function _mcryptDecode( $data )
    {
        $ivSize = mcrypt_get_iv_size($this->_cipher, $this->_mode);
        
        $iv = substr($data, 0, $ivSize);
        $data = substr($data, $ivSize);
        
        return rtrim( mcrypt_decrypt($this->_cipher, $this->_key, $data, $this->_mode, $iv), '\0');
    }
}

/* End of file Encrypt.php */
